﻿jetpack.future.import("slideBar");
jetpack.future.import("storage.simple");

var manifest = {
  settings: [
    { name: "is_auto", type: "boolean", label: "自动买卖", default: true },
    { name: "buy_factor", type: "range", label: "购买系数", min: 0, max: 10, default: 2 },
    { name: "near_factor", type: "range", label: "接近峰值", min: 0, max: 10, default: 1 },
    { name: "auto_period", type: "number", label: "自动买卖间隔(Min)" ,default:10}
  ]
};
   
jetpack.future.import("storage.settings");
 set = jetpack.storage.settings;


function KaiXinRich(){
    var self = this;
    self.mvp=[];
    self.totalMoney=0;
    self.cash=0;
    self.is_running;

    self.storage=jetpack.storage.simple;
    self.storage.products=self.storage.products? self.storage.products:[];

    self.buy_count=[];
    for(var i=1;i<=20;i++){ self.buy_count.push(i);}
    self.buy_count.push(100);
    self.buy_count.push(200);
    self.buy_count.push(500);
    self.buy_count.push(1000);    

    self.myitem=[];

    self.enable=function(){
        clearInterval(self.is_running);
        self.update();

        self.is_running = setInterval(self.update, 3*1000);
        console.log("KaiXinRich: Enabled");
    return true;
    }
    this.init();
};
KaiXinRich.prototype={
    product:function(iid,cateid,name,min_price,max_price){
        return {iid:iid,cateid:cateid,name:name,min_price:min_price,max_price:max_price};
    },
    order:function(product,current_price,buy_count,profits){
        return {product:product,current_price:current_price,buy_count:buy_count,profits:profits};
    },
    readProduct:function(iid){
        return this.storage.products[iid-1];
    },
    resetStore:function(){
        this.storage.products=[];
    },
    updatePrice:function(iid,cateid,name,current_price){
        var p=this.readProduct(iid);

      //  this.storage.products.forEach(function(p){
         //  if(p.iid==iid){
        if(p){
             p.name=name;
              p.cateid=cateid;
             p.min_price=current_price<p.min_price?current_price:p.min_price;
             p.max_price=current_price>p.max_price?current_price:p.max_price;
            }else{
            p=this.product(iid,cateid,name,current_price,current_price);
            }
            this.storage.products[iid-1]=p;
     //   });
    },
    putmvp:function(iid,current_price){  
          if(current_price-this.cash>0) return;
        var p=this.readProduct(iid);
        if(!p) {
            console.log("product iid"+iid+" was not found");
            return;
         };
            
            var profits=p.max_price-current_price;
            //expected profit
            var ep=Number.MIN_VALUE;
            var num=0;
         // console.log("mvp "+iid+" currp: "+current_price+" profits: "+profits);
       
            for(var bc=0;bc<this.buy_count.length;bc++){
                var i=this.buy_count[bc];
                var gp=i*profits;
if(p.cateid>1 && i>20){
                break;
            }
            //console.log("ii:        "+i);
           // console.log(i*current_price>=this.cash && gp>ep);
                if(gp>ep && (i*current_price<=this.cash)){
                    ep=gp;
                    num=i;
                   // console.log("ep: "+ep);
                }
            }
            //product,current_price,buy_count,profits
            var order=this.order(p,current_price,num,ep);
            
            var notinsert=false;


        if(this.totalMoney>=1000000 && order.product.cateid==1){
                    return ;
            }
            this.mvp.push(order);
    },
    buyOne:function(iid){
         this.mvp.forEach(function(order){
                    if(order && order.product.iid==iid){
                        self.buyProduct(order);                
                       return;
                    }
            });
    },
    sellOne:function(iid){
         this.myitem.forEach(function(order){
                    if(order && order.product.iid==iid){
                        self.sellProduct(order);                
                       return;
                    }
            });
    },
    imRich:function(){
    console.log("KaiXinRich: auto-management is running ");
        this.updateMyItem();
        this.autoSell(set.near_factor/10);
        this.updateProfile();
        this.update();
        this.autoBuy(set.near_factor/10);        
        
    },
    autoBuy:function(tv){
               var ctv;
        //if(this.myitem.length>1) {console.log("max item "+ this.myitem.length+1);return;}
        for(od=0;od<5;od++){
            var item=this.mvp[od];
            if(item){
                 ctv=(item.current_price-item.product.min_price)*2/(item.product.max_price-item.product.min_price)
                   // console.log(ctv);
                    if(ctv<=tv&& this.totalMoney*set.buy_factor/10<item.profits){
                        this.buyProduct(item);
                    }                
                }
        }
    },
    autoSell:function(tv){
            var ctv;
        for(od=0;od<this.myitem.length;od++){
            var item=this.myitem[od];
            if(item){
                 ctv=(item.product.max_price-item.current_price)*2/(item.product.max_price-item.product.min_price)
                    //console.log(od+item.product.name+"  sell ctv"+ctv+"max"+item.product.max_price); 
                if(ctv<=tv){
                        this.sellProduct(item);
                    }                
                }
        }
    },
    buyProduct:function(order){
         $.post(this.webRoot+"!purchase.php?iid="+order.product.iid+"&purchase_price="+order.current_price+"&t="+Math.random(), 
                { iid: order.product.iid, num:order.buy_count,purchase_price:order.current_price},
                 function(data){
                      if(data.indexOf("$(\"display_99\").style.display")>0){
                            var patt=/<b>你成功[^;]+span>/;
                            var msg=data.match(patt);        
                            
                            jetpack.notifications.show({
                                title: "大亨提示",
                                body: msg, 
                                icon: "http://img.kaixin001.com/i3/dh/icon_28.gif"
                            }); 
                        console.log("KaiXinRich: bought "+order.product.name+" X "+order.buy_count);
                        }else{
                        console.log("buying "+order.product.name+" not success");    
                        }
                  });
    },
    sellProduct:function(order){
        var sell_num =0;
       for(var bc=0;bc<this.buy_count.length;bc++){
                var i=this.buy_count[bc];
                if(order.buy_count>=i) sell_num=i;
        }
            //sell_num 
            sell_num = order.buy_count;
        
        var cost_price=order.current_price-order.profits/order.buy_count;


        $.post(this.webRoot+"!sell.php?iid="+order.product.iid+"&cost_price="+cost_price+"&sell_price="+order.current_price+"&t="+Math.random(), 
                { iid: order.product.iid, num:sell_num,sell_price:order.current_price},
                 function(data){
                                if(data.indexOf("$(\"display_99\").style")>0){
                            var patt=/你成功售出[^;]+span>/;
                            var msg=data.match(patt);        
                                        
                            jetpack.notifications.show({
                                title: "大亨提示",
                                body: msg, 
                                icon: "http://img.kaixin001.com/i3/dh/icon_28.gif"
                            }); 
                console.log("KaiXinRich: sold out "+order.product.name+" X "+sell_num);
        
                        }else{
                        console.log("selling "+order.product.name+" not success");    
                        }
                  });
    },
    update:function(html){
        console.log("KaiXinRich: mvp updating...");
        this.mvp=[];
        
       // this.updateCate(1); 
        this.updateCate(2);
        this.updateCate(2,20);
        this.updateCate(4);
        this.updateCate(7);
        this.updateCate(8);
        this.updateCate(9);
        this.updateCate(10);
        this.updateCate(11);
        
		    quickSort(this.mvp, sortContainer);  
        console.log("KaiXinRich: mvp updated");
        //this.printProducts();
    },
    updateCate:function(cateid,page,ignore){
        self=this;
        $.ajax({
           type:"GET",
           url:this.webRoot+"market.php",
           data:({cateid:cateid,start:page}),
           async:false,
           cache:false,
           success:function(data) {  
                var  pattern=/javascript:purchase\(.+(?=\))/g;
                var arrdata = data.match(pattern);
                var  namep=/alt=".+?"/g;  
                var  arrnames=data.match(namep);
   
                for (var i = 0; i < arrdata.length; i++)
                {
                        arrdata[i]=arrdata[i].replace("javascript:purchase(","").replace("'","").replace("'","");
                    if(!arrnames[i]){
                        // console.log(i +"   "+ cateid);
                            continue;
                        }
                        arrnames[i]=arrnames[i].replace("alt=\"","").replace("\"",""); 
                        var tema=arrdata[i].split(",");
                        var iid=tema[0].trim();
                        var currp=parseInt(tema[1].trim());
                // console.log(iid +"\t"+currp+"\t"+arrnames[i]);  
                        self.updatePrice(iid,cateid,arrnames[i],currp);
                        self.putmvp(iid,currp);
                }
               // console.log(cateid+" "+page +"updated")
            }
        });  
    },
    updateProfile:function(){
            var self=this;
         $.ajax({
            type:"GET",
            url:this.webRoot+"index.php",
           cache: false,
           async: false,
          success:function(data) { 
            //<b>现金：2万6760元</b>
            var cashp=/<b>现金：.+?<\/b>/;
            var cashm=data.match(cashp)[0];
                cashm=cashm.replace("<b>现金：","");
                cashm=cashm.replace("元</b>","");
          
            self.cash=parseWan(cashm);
               
                cashp=/<b>资产：.+?<\/b>/;
                cashm=data.match(cashp)[0];
                cashm=cashm.replace("<b>资产：","");
                cashm=cashm.replace("元</b>","");
                self.assets=parseWan(cashm);
                self.totalMoney=self.assets+self.cash;
         console.log(new Date()+"KaiXinRich: profile updated. total: "+self.totalMoney+
        " cash: "+self.cash+" assets: "+self.assets);
            }
        });
     return self.cash;
    },
    updateMyItem:function(){
          this.myitem=[];
              var self=this;
         $.ajax({
            type:"GET",
            url:this.webRoot+"myitem.php",
           cache: false,
          async: false,
          success:function(data) { 
         
            var namep=/javascript:sell\(.+(?=\))/g;
           var  arrdata=data.match(namep);
         //   var nump=/\s\d+(?=\w+\s)/;
                var nump=/\s\d+(?=.+?<img)/g;
            var arrnum=data.match(nump);
        if(!arrdata) return;
       for (var i = 0; i < arrdata.length; i++)
       {
           if(!arrnum[i]){
               
                continue;
            }
           
            arrnum[i]=parseInt(arrnum[i].trim());
            arrdata[i]=arrdata[i].replace("javascript:sell(","").replace("'","").replace("'","");
            var tema=arrdata[i].split(",");
            var iid=tema[0].trim();
            var buyp=parseInt(tema[1].trim());
            var currp=parseInt(tema[2].trim());
            var profits=(currp-buyp)*arrnum[i];

            var p=self.readProduct(iid);
            if(p){
                var order=self.order(p,currp,arrnum[i],profits);
              //  console.log(currp+"  "+ arrnum[i]+"  "+profits+"  "+ p.name);
                self.myitem.push(order);
            }
            }
}
        }); 
    console.log("KaiXinRich: myitem updated");    
    },
    printProducts:function(){
        this.storage.products.forEach(function(p){console.log(p?p.name+"\t"+p.iid+"\t"+p.min_price+"\t"+p.max_price:"null");});

    },
    init:function(){
        this.updateProfile();
       // this.updateMyItem();
    },
    webRoot:"http://www.kaixin001.com/!rich/"
}
jetpack.slideBar.append({
    icon:"http://img.kaixin001.com/i3/dh/icon_28.gif",
    width: 250,
    onReady:function(slider){
        rich=new KaiXinRich();
        //rich.update();
        rich.imRich();
       

	if(set.is_auto){
 		rich.is_running=setInterval( function() { rich.imRich() }, 60*1000*set.auto_period );
		console.log("auto run enabled");
	}else{
		clearInterval(rich.is_running);
		console.log("auto run disabled");
	}
       
         
           
           
           
        $(slider.contentDocument).find("#update").click(function(){
       			 refresh();
        });
        
        refresh=function(){
            rich.updateProfile();
            rich.updateMyItem();
            rich.update();
      			drawUI();
        }
        
        drawUI=function(){
        		var scontent=$(slider.contentDocument);
 	scontent.find("#profile").html("<h3>总资产："+rich.totalMoney+
                    "</h3><h4>现金："+
                    rich.cash+"</h4><h4>资产："+rich.assets+
                "</h4>");
     			scontent.find("items").html("");
					scontent.find("orders").html("");
          rich.myitem.forEach(function(order){
	           	scontent.find("items").append("<li>"+
	            order.product.name+" "+
	            order.current_price+"元 "+
	            order.buy_count+"个 "+order.profits+
	                "<b name='"+order.product.iid+"' class='sell'>sell</b></li>"); 
	
	            });
       
      //  rich.mvp.forEach(function(order){
        for(var m=0;m<rich.mvp.length;m++){
              var order=rich.mvp[m];
            if(!order) continue;
           scontent.find("orders").append("<li>"+
            order.product.name+" "+
            order.current_price+"元 "+
            order.buy_count+"个 "+order.profits+
                "<b name='"+order.product.iid+"' class='buy'>buy</b></li>"); 

        }
            scontent.find(".buy").click(function(){
                    var o=$(this).attr("name");
                    console.log(o);
                    rich.buyOne(o);                

                  });
  				scontent.find(".sell").click(function(){
                    var o=$(this).attr("name");
                    console.log(o);
                    rich.sellOne(o);                

                  });
      }
        
    },
 onClick: function(slider) {
 					drawUI();
      	
  },

html:"<body><b id='update'>update</b><div id='profile'></div><items></items>-------------<div id='container'><orders></orders></div></body>"
});
console.log("i'm jmu ,i will start my first jetpack now!");

function test(){
   var rich=new KaiXinRich();
   // rich.enable();
///console.log(rich.storage.products.length);
rich.storage.products.forEach(function(p){console.log(p?p.name+"\t"+p.iid+"\t"+p.min_price+"\t"+p.max_price:"null");});
 
}
//test(); 


   var sortContainer=   
  {   
      compare: function(v1, v2)   
     {   
            if(!v1 || !v2) return 0;
         if (v1.profits==v2.profits)   
              return 0;   
         else if (v1.profits<v2.profits)   
            return 1;   
         else  
            return -1;   
    },   
  
     swap: function(i1, i2)   
     {   
     }          
 
}   
   
   function quickSort(a, container)   
  {   
    if (a==null)   
        return;   
      var length=a.length;   
    if (length<2)   
         return;   
     function internalQuickSort(lowIndex, highIndex, a, container)   
      {   
         if (lowIndex<highIndex)   
          {   
             var pos=internalPartition(lowIndex, highIndex, a, container);   
            internalQuickSort(lowIndex, pos-1, a, container);   
             internalQuickSort(pos+1, highIndex, a, container);   
        }   
      }   
     function internalPartition(lowIndex, highIndex, a, container)   
     {   
          var pivot=a[lowIndex];   
          var lowI=lowIndex;   
         var highI=highIndex;   
         while (true)   
          {   
              do {lowI++;} while (container.compare(a[lowI], pivot)<0);   
             while (container.compare(a[highI], pivot)>0) {highI--;}   
            if (lowI>=highI) break;   
             var tmp=a[lowI];   
            a[lowI]=a[highI];   
             a[highI]=tmp;   
             container.swap(lowI, highI);   
              if (container.debug) container.debug("* "+lowI+"("+a[highI]+") -&gt; "+highI+"("+a[lowI]+") ["+a.join(",")+"]");   
        }   
         if (lowIndex!=highI)   
       {   
            a[lowIndex]=a[highI];   
           a[highI]=pivot;   
            container.swap(lowIndex, highI);   
          if (container.debug) container.debug(lowIndex+"("+a[highI]+") -&gt; "+highI+"("+a[lowIndex]+") ["+a.join(",")+"]");   
       }   
        return highI;   
    }   
     if (container.debug) container.debug("["+a.join(",")+"]");   
     internalQuickSort(0, length-1, a, container);   
      if (container.debug) container.debug("["+a.join(",")+"]");   
 }   
       function parseWan(cashm){
                        var y="亿";
                      var w="万";
                        var resualt=0;
                if(cashm.indexOf(y)>0){
                    var t=cashm.split(y);
                    resualt=parseInt(t[0])*100000000;
                    cashm=t[1];
                }
                if(cashm.indexOf(w)>0){
                        var tema=cashm.split(w);
                        resualt+=parseInt(tema[0])*10000;
                        if(tema[1].length>0) resualt+=parseInt(tema[1]);
                }else{
                     resualt=parseInt(cashm);
                }
                return resualt;
            }

